package cn.chinasyq.photoquan.news.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import cn.chinasyq.photoquan.AppConstant;
import cn.chinasyq.photoquan.R;
import cn.chinasyq.photoquan.news.adapter.ArticlesListAdapter;
import cn.chinasyq.photoquan.news.bean.ArticlesEntity;
import cn.chinasyq.photoquan.news.bean.ArticlesList;
import cn.chinasyq.photoquan.news.bean.BannersEntity;
import cn.chinasyq.photoquan.news.mode.NewsMode;
import cn.chinasyq.photoquan.util.TimeUtil;
import cn.chinasyq.photoquan.view.LoadView;
import cn.master.util.utils.ToastUtil;
import cn.master.volley.models.response.handler.ResponseHandler;
import cn.master.volley.models.response.handler.ResponseHandler.OnFailedListener;
import cn.master.volley.models.response.handler.ResponseHandler.OnSucceedListener;
import cn.master.xlistview.view.XListView;
import cn.master.xlistview.view.XListView.IXListViewListener;
import cn.master.xlistview.view.XListView.RefreshTimeListener;

/**
 * Created by 一搏 on 2015/11/24.
 */
public class NewsSearchActivity extends Activity implements OnFailedListener, OnSucceedListener, IXListViewListener, RefreshTimeListener, TextView.OnEditorActionListener, View.OnClickListener {
    private ImageButton ibtn_del;
    private XListView lv_content;
    private LoadView loadView;
    private final String TAG_REFRENSH = "refresh";
    private final String TAG_LOAD_MORE = "loadmore";
    private ArticlesListAdapter adapter;
    private String keyword;
    private EditText et_search;
    private Button btn_cancle;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_news);
        ibtn_del = (ImageButton) findViewById(R.id.ibtn_del);
        ibtn_del.setOnClickListener(this);
        btn_cancle = (Button) findViewById(R.id.btn_cancle);
        btn_cancle.setOnClickListener(this);
        lv_content = (XListView) findViewById(R.id.xlv_content);
        loadView = (LoadView) findViewById(R.id.loadview);
        et_search = (EditText) findViewById(R.id.et_search);
        et_search.setOnEditorActionListener(this);
        loadView.setOnReLoadClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadView.setStatus(LoadView.Status.loading);
                refresh();
            }
        });
        lv_content.setXListViewListener(this);
        lv_content.setRefreshTimeListener(this);
        lv_content.setPullLoadEnable(false);
        adapter = new ArticlesListAdapter();
        lv_content.setAdapter(adapter);
        lv_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (parent.getItemAtPosition(position) instanceof ArticlesEntity) {
                    Intent intent = new Intent(getApplicationContext(), ArticleInfoActivity.class);
                    intent.putExtra(ArticleInfoActivity.UUID, ((ArticlesEntity) parent.getItemAtPosition(position)).getUuid());
                    startActivity(intent);
                }
            }
        });
    }


    private void refresh() {
        ResponseHandler handler = new ResponseHandler(TAG_REFRENSH);
        handler.setOnSucceedListener(this);
        handler.setOnFailedListener(this);
        NewsMode.searchActiclesList(handler, keyword);
    }

//    private void loadmore() {
//        ResponseHandler handler = new ResponseHandler(TAG_LOAD_MORE);
//        handler.setOnSucceedListener(this);
//        handler.setOnFailedListener(this);
//        NewsMode.obtainActiclesList(handler, NewsMode.MODE_LOAD_MORE);
//    }

    @Override
    public void onFailed(String tag, ResponseHandler.FailedStatus status, int resultCode, String msg) {
        if (msg == null) {
            switch (status) {
                case DATA_ERROR:
                    ToastUtil.show(getApplicationContext(), R.string.tip_data_error);
                    break;
                case NETWORK_ERROR:
                    ToastUtil.show(getApplicationContext(), R.string.servererrortips);
                    break;
            }
        } else {
            ToastUtil.show(getApplicationContext(), msg);
        }

        if (TAG_REFRENSH.equals(tag)) {
            if (loadView.getStatus() != LoadView.Status.successed) {
                loadView.setStatus(status == ResponseHandler.FailedStatus.DATA_ERROR ? LoadView.Status.data_error : LoadView.Status.network_error);
            }
            lv_content.stopRefresh();
        }
        if (TAG_LOAD_MORE.equals(tag)) {
            lv_content.stopLoadMore();
        }
    }

    @Override
    public void onSucceed(String tag, boolean isCache, Object data) {
        if (TAG_REFRENSH.equals(tag)) {
            ArticlesList bean = (ArticlesList) data;
            List<ArticlesEntity> posters = bean.getArticles();
            List<BannersEntity> matches = bean.getBanners();
            refreshData(isCache, posters);

        }
        if (TAG_LOAD_MORE.equals(tag)) {
            ArticlesList beans = (ArticlesList) data;
            loadMoreData(beans.getArticles());
        }
    }

    /**
     * 刷新数据
     */
    private void refreshData(boolean isCache, List<ArticlesEntity> beans) {
        if (!isCache) {
            if (beans == null || beans.size() == 0) {
                loadView.setStatus(LoadView.Status.not_data);
            } else {
                loadView.setStatus(LoadView.Status.successed);
                adapter.setArticlesEntities(beans);
            }
            lv_content.setSelection(0);
        }
        saveLastUpdateTime();
        lv_content.stopRefresh();
    }


    /**
     * 保存最后更新时间
     */
    private void saveLastUpdateTime() {
        SharedPreferences.Editor lastUpdateTimeEditor = getApplicationContext().getSharedPreferences(
                AppConstant.LastUpdateTimeKey.LAST_UPDATE_TIME.toString(),
                Context.MODE_PRIVATE).edit();
        lastUpdateTimeEditor.putLong(
                AppConstant.LastUpdateTimeKey.FINISHED_NEWS.toString(),
                System.currentTimeMillis()).commit();
    }

    @Override
    public void onRefresh() {
        refresh();
    }


    /**
     * 加载更多
     */
    private void loadMoreData(List<ArticlesEntity> beans) {
        if (beans == null || beans.size() == 0) {
            ToastUtil.show(getApplicationContext(), R.string.no_more, Toast.LENGTH_SHORT);
        } else {
            adapter.addArticlesEntities(beans);
        }
        lv_content.stopLoadMore();
    }

    @Override
    public void onLoadMore() {
//        loadmore();
    }

    @Override
    public void onRefreshTime(TextView view) {
        view.setText(TimeUtil.obtainLastUpdateTimeStatuString(getApplicationContext(), getApplicationContext()
                .getSharedPreferences(
                        AppConstant.LastUpdateTimeKey.LAST_UPDATE_TIME.toString(), 0)
                .getLong(AppConstant.LastUpdateTimeKey.FINISHED_NEWS.toString(), 0)));
    }

    public void onItemFirstShow() {
        ArticlesList bean = NewsMode.getActiclesListByCache();
        if (bean != null) {
            List<ArticlesEntity> matches = bean.getArticles();
            if (matches != null) {
                if (matches.size() > 0) {
                    loadView.setStatus(LoadView.Status.successed);
                } else {
                    loadView.setStatus(LoadView.Status.not_data);
                }
                adapter.setArticlesEntities(matches);
            }
            lv_content.firstRefresh();
        } else {
            loadView.setStatus(LoadView.Status.loading);
            onRefresh();
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (KeyEvent.KEYCODE_ENTER==event.getKeyCode()&&KeyEvent.ACTION_UP == event.getAction()) {
            keyword = v.getText().toString();
            refresh();
        }

        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_cancle:
                onBackPressed();
                break;
            case R.id.ibtn_del:
                et_search.setText("");
                break;

        }
    }
}
